package com.shushan.login;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.db.ChildBeanDao;
import com.shushan.db.ChildBookDao;
import com.shushan.home.TabHomeActivity;
import com.shushan.login.bean.ChildBookBean;
import com.shushan.setting.BookSelectActivity;
import com.shushan.setting.ChildSettingActivity;
import com.shushan.setting.ParentPswSetActivity;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName: VerificationCodeActivity
 * @Desciption: //用户填写验证码的界面
 * @author: zhangshihao
 * @date: 2018-03-28
 */
public class VerificationCodeActivity extends BaseActivity implements VerificationCodeView.OnCodeFinishListener, View.OnClickListener {

    private static final String TAG = VerificationCodeActivity.class.getSimpleName();

    private VerificationCodeView mVeriCodeView;
    private TextView mTvSeconds,mTvPhoneNum;
    private ImageButton ivBack;

    private Timer mTimer;
    private Dialog mDialog;

    private String mobile;
    private String msgId;
    private String code;
    private int start = 60;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                int currSecond = msg.arg1;
                if (currSecond >= 0) {
                    mTvSeconds.setText(String.valueOf(currSecond) + "秒后可重新发送");
                } else {
                    mTvSeconds.setTextColor(Color.rgb(68, 68, 68));
                    mTvSeconds.setText("重新发送");
                    if(mTimer != null) {
                        mTimer.cancel();
                    }
                    mTvSeconds.setOnClickListener(VerificationCodeActivity.this);
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verification);

        Log.i(TAG,"onCreate()");

        ScreenManager sm = new ScreenManager();
        sm.setStatusBar(true,this);

        mobile = getIntent().getStringExtra("mobile");
        msgId = getIntent().getStringExtra("msgId");
        code = getIntent().getStringExtra("code");

        initView();

        countBackwardOneMinute();

        if(BuildConfig.DEBUG){
            showCodeDialog(code);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.i(TAG,"onDestroy()");

        if(mTimer != null) {
            mTimer.cancel();
        }
        if(mDialog != null && mDialog.isShowing()){
            mDialog.dismiss();
        }
        recycle();
    }

    private void initView() {
        mVeriCodeView = (VerificationCodeView) findViewById(R.id.verification_code_view);
        mTvSeconds = (TextView) findViewById(R.id.tv_seconds);
        mTvPhoneNum = (TextView) findViewById(R.id.tv_phone_num);
        ivBack = (ImageButton) findViewById(R.id.iv_back);
        mVeriCodeView.setOnCodeFinishListener(this);
        ivBack.setOnClickListener(this);
        mTvPhoneNum.setText(mobile);
    }

    @Override
    public void onComplete(String code) {
        //判断用户输入的验证码是否正确
        if(!(TextUtils.isEmpty(code) || code.length() < 4)){
            verifyCode(mobile,code,msgId);
        }
    }

    private void countBackwardOneMinute() {
        mTimer = new Timer();

        if (mTvSeconds.hasOnClickListeners()) {
            mTvSeconds.setOnClickListener(null);
        }
        mTvSeconds.setTextColor(Color.rgb(188,188,188));
        mTimer.schedule(new CountBackwardTask(), 0, 1000);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_seconds:
                sendVerCode(mobile);
                break;
            case R.id.iv_back:
                showConfirmBackDialog();
                break;
            case R.id.btn_back:
                if(mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                onBackAction();
                break;
            case R.id.btn_wait:
                if(mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            showConfirmBackDialog();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showConfirmBackDialog(){
        mDialog = new Dialog(this, R.style.Dialog_Translucent_Background);
        mDialog.setContentView(R.layout.dialog_back_confirm);
        Button btnBack = mDialog.findViewById(R.id.btn_back);
        Button btnWait = mDialog.findViewById(R.id.btn_wait);
        btnBack.setOnClickListener(this);
        btnWait.setOnClickListener(this);
        mDialog.setCancelable(false);
        mDialog.show();
    }

    private void recycle() {
        mHandler = null;
        mTimer = null;
    }

    class CountBackwardTask extends TimerTask {
        @Override
        public void run() {
            start -= 1;
            Message msg = new Message();
            msg.what = 0;
            msg.arg1 = start;
            mHandler.sendMessage(msg);
        }
    }

    private void sendVerCode(final String mobile) {
        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this , UrlConst.BASE_URL).appendRegion(UrlConst.SEND_VER_CODE);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("debug", BuildConfig.DEBUG ? 1 : 0)
                .putValue("phone", mobile);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST,new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        Log.i(TAG,"onSuccess data=" + data);

                        start = 60;
                        countBackwardOneMinute();

                        String code = "";
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            msgId = jsonObject.optString("msgid","");
                            code = jsonObject.optString("code", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if(BuildConfig.DEBUG){
                            showCodeDialog(code);
                        }else {
                            showToast("验证码发送成功");
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void verifyCode(final String mobile, String code, String msgId) {
        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this,UrlConst.BASE_URL).appendRegion(UrlConst.LOGIN_OR_REGISTER);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("phone", mobile)
                .putValue("code", code)
                .putValue("msgid", msgId);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST,new NetSingleCommListener<UserBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(UserBean userBean) {
                        Log.i(TAG,"onSuccess userBean=" + userBean.toString());

                        UmengEventUtil.onProfileSignIn(mobile);

                        SharedPreferencesUtils.setBooleanDate(Constants.APP_NOT_FIRST_SHAREPREFERS_KEY,true);
                        SharedPreferencesUtils.setStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY,mobile);

                        if(userBean != null){
                            shuShanApplication.setUserBean(userBean);

                            SharedPreferencesUtils.setStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY,userBean.password);

                            final PushAgent mPushAgent = PushAgent.getInstance(VerificationCodeActivity.this);
                            int currentChildId = shuShanApplication.getCurrentChildId();
                            if(currentChildId > 0){
                                mPushAgent.setAlias(currentChildId+"", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                                    @Override
                                    public void onMessage(boolean isSuccess, String message) {
                                        Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                                    }
                                });
                            }

                            int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
                            if(useId > 0){
                                mPushAgent.setAlias(useId+"", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                                    @Override
                                    public void onMessage(boolean isSuccess, String message) {
                                        Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                                    }
                                });
                            }

                            List<ChildBean> childList = userBean.getChildList();
                            if(childList.size() > 0){
                                new ChildBeanDao(shuShanApplication).dropAndAddList(childList);

                                ChildBean childBean = childList.get(0);
                                new ChildBookDao(shuShanApplication).clearTab();
                                if(ToolUtils.isListEmpty(childBean.getBookBeanList())){
                                    Intent intent = new Intent(VerificationCodeActivity.this,BookSelectActivity.class);
                                    intent.putExtra("gradeId",childBean.gradeId);
                                    intent.putExtra("semester",childBean.semester);
                                    intent.putExtra("firstTime",1);
                                    startActivityAllow(intent);

                                }else {
                                    List<ChildBookBean> bookBeanList = childBean.getBookBeanList();
                                    new ChildBookDao(shuShanApplication).addOrUpdateList(bookBeanList);

                                    if(!TextUtils.isEmpty(userBean.password)){
                                        SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,true);
                                        Intent intent = new Intent(VerificationCodeActivity.this,TabHomeActivity.class);
                                        intent.putExtra("firstTime",1);
                                        startActivityAllow(intent);
                                    }else {
                                        Intent intent = new Intent(VerificationCodeActivity.this,ParentPswSetActivity.class);
                                        intent.putExtra("firstTime",1);
                                        startActivityAllow(intent);
                                    }
                                }


                            }else {
                                new ChildBeanDao(shuShanApplication).clearTab();

                                Intent intent = new Intent(VerificationCodeActivity.this,ChildSettingActivity.class);
                                intent.putExtra("firstTime",1);
                                startActivityAllow(intent);
                            }
                        }else {
                            Intent intent = new Intent(VerificationCodeActivity.this,ChildSettingActivity.class);
                            intent.putExtra("firstTime",1);
                            startActivityAllow(intent);
                        }

                        ActivityStackManager.getActivityStackManager().popActivity("LoginOrRegisterActivity");
                        onBackAction();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                        for(int i=0;i<mVeriCodeView.getmEtNumber();i++){
                            EditText et = (EditText)mVeriCodeView.getChildAt(i);
                            et.setText("");
                            if(i == 0){
                                et.setFocusable(true);
                                et.requestFocus();
                            }
                        }
                    }
                });
    }

    private void showCodeDialog(String code) {
        new CustomDialog.Builder(this)
            .setTitle("温馨提示")
            .setMessage("【书山宝】 验证码：" + code + ",书山用户，您正在使用手机账号登陆，请您在5分钟内完成验证。")
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .create().show();
    }
}
